package com.weihe.toolkit.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * HTTP工具箱
 */
public final class HttpToolkit {
	private static final Log log = LogFactory.getLog(HttpToolkit.class);
	
	private static final String DEFAULT_CHARSET = "UTF-8";

	/**
	 * 执行一个HTTP GET请求
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param queryString
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @return 返回请求的响应
	 */
	public static ResponseRawObject doGet(String url,  Map<String, String> params, String charset) {
		ResponseRawObject restResponse = null;
		if(StringUtils.isNotBlank(url)){
			HttpMethod method = new GetMethod(url);
			setMethodParams(method,params);
			try {
				restResponse = sendRequest(method,charset);
			} catch (IOException e) {
				log.error("执行HTTP Get请求" + url + "时，发生异常！", e);
			}catch (Exception e) {
				log.error("执行HTTP Get请求" + url + "时，发生异常！", e);
			} finally {
				method.releaseConnection();
			}
		}
		return restResponse;
	}
	
	public static ResponseRawObject doGet(String url,  Map<String, String> params){
		return doGet(url,params,DEFAULT_CHARSET);
	}

	/**
	 * 执行一个HTTP POST请求
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param params
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @return 返回请求的响应
	 */
	public static ResponseRawObject doPost(String url, Map<String, String> params,
			String charset) {
		ResponseRawObject restResponse = null;
		if(StringUtils.isNotBlank(url)){
			restResponse = new ResponseRawObject();
			HttpMethod method = new PostMethod(url);
			setMethodParams(method,params);
			try {
				restResponse = sendRequest(method,charset);
			} catch (Exception e) {
				log.error("执行HTTP Post请求" + url + "时，发生异常！", e);
			} finally {
				method.releaseConnection();
			}
		}
		return restResponse;
	}
	
	public static ResponseRawObject doPost(String url, Map<String, String> params){
		return doPost(url,params,DEFAULT_CHARSET);
	}
	
	/**
	 * 执行一个HTTP DELETE请求
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param params
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @return 返回请求的响应
	 */
	public static ResponseRawObject doDelete(String url, Map<String, String> params,
			String charset) {
		ResponseRawObject restResponse = null;
		if(StringUtils.isNotBlank(url)){
			restResponse = new ResponseRawObject();
			HttpMethod method = new DeleteMethod(url);
			setMethodParams(method,params);
			try {
				restResponse = sendRequest(method,charset);
			} catch (Exception e) {
				log.error("执行HTTP Delete请求" + url + "时，发生异常！", e);
			} finally {
				method.releaseConnection();
			}
		}
		return restResponse;
	}
	
	public static ResponseRawObject doDelete(String url, Map<String, String> params){
		return doDelete(url,params,DEFAULT_CHARSET);
	}
	
	/**
	 * 执行一个HTTP PUT请求
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param params
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @return 返回请求的响应
	 */
	public static ResponseRawObject doPut(String url, Map<String, String> params,
			String charset) {
		ResponseRawObject restResponse = null;
		if(StringUtils.isNotBlank(url)){
			restResponse = new ResponseRawObject();
			HttpMethod method = new PutMethod(url);
			setMethodParams(method,params);
			try {
				restResponse = sendRequest(method,charset);
			} catch (Exception e) {
				log.error("执行HTTP PUT请求" + url + "时，发生异常！", e);
			} finally {
				method.releaseConnection();
			}
		}
		return restResponse;
	}
	
	public static ResponseRawObject doPut(String url, Map<String, String> params){
		return doPut(url,params,DEFAULT_CHARSET);
	}
	
	public static void setMethodParams(HttpMethod method,Map<String,String> map){
		if(null != map && !map.isEmpty()){
			NameValuePair[] data = new NameValuePair[map.size()];
			int i=0;
			for (Map.Entry<String, String> entry : map.entrySet()) {
				data[i++] = new NameValuePair(entry.getKey(), entry.getValue());
			}
			method.setQueryString(data);
		}
	}
	
	public static ResponseRawObject sendRequest(HttpMethod method, String charset)
			throws Exception {
		ResponseRawObject restResponse = null;
		if (null != method) {
			restResponse = new ResponseRawObject();
			try {
				HttpClient client = new HttpClient();
				restResponse.setResponseCode(client.executeMethod(method));
				StringBuffer response = new StringBuffer();
				BufferedReader reader = null;
				if(StringUtils.isBlank(charset)){
					charset = DEFAULT_CHARSET;
				}
				try {
					reader = new BufferedReader(new InputStreamReader(
							method.getResponseBodyAsStream(), charset));
					String line;
					while ((line = reader.readLine()) != null) {
						response.append(line).append(System.getProperty("line.separator"));
					}
				} finally {
					if (null != reader) {
						reader.close();
					}
					restResponse.setResponseText(response.toString());
				}
			} finally {
				method.releaseConnection();
			}
		}
		return restResponse;
	}
}

